package com.springboot.service;


import com.springboot.constant.CommonConstant;
import com.springboot.domain.*;
import com.springboot.dto.PersonDetailDTO;
import com.springboot.dto.PersonModifyDTO;
import com.springboot.repository.*;
import com.springboot.tools.ResultUtil;
import com.springboot.tools.UUIDTool;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpSession;
import javax.transaction.Transactional;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

/**
 * Created by Administrator on 2017/7/12.
 */
@Slf4j
@Service
@Transactional
public class PersonalService {

    @Value("${spring.mail.username}")
    private String username;
    private final PersonRepository personRepository;
    private final DemandRepository demandRepository;
    private final FileRepository fileRepository;
    private final SkillsRepository skillsRepository;
    private final PersonSkillsRepository personSkillsRepository;

    @Autowired
    public PersonalService(FileRepository fileRepository, PersonRepository personRepository, DemandRepository demandRepository, SkillsRepository skillsRepository, PersonSkillsRepository personSkillsRepository) {
        this.fileRepository = fileRepository;
        this.personRepository = personRepository;
        this.demandRepository = demandRepository;
        this.skillsRepository = skillsRepository;
        this.personSkillsRepository = personSkillsRepository;
    }


    public Result findPersonDetailById(String id) {
        Result<PersonDetailDTO> personDetails = findPersonDetails(id);
        if (!personDetails.getABoolean()) {
            return personDetails;
        }
        int total = personDetails.getData().getViews() + 1;
        personRepository.addViews(total, personDetails.getData().getId());
        return personDetails;
    }

    public Result findPersonDetails(String id) {
        BtPerson person = personRepository.findOne(id);
        if (person == null) {
            return ResultUtil.error("没有此信息！");
        }
        PersonDetailDTO personDetailDTO = new PersonDetailDTO();
        BeanUtils.copyProperties(person, personDetailDTO);
        String ids = fileRepository.findFileId(person.getId(), "headPicture");
        personDetailDTO.setIds(ids);

        List<Integer> skillIds = personSkillsRepository.findSkillsByUserId(id);
        List<BtSkills> skills = skillsRepository.findAllByIdIn(skillIds);
        personDetailDTO.setSkills(skills);

        return ResultUtil.success(personDetailDTO);
    }

    public void updatePersonById(PersonModifyDTO personModifyDTO, HttpSession session) {
        String id = session.getAttribute("user").toString();
        List<Integer> skillIds = personModifyDTO.getSkillIds();
        // 技能项处理
        //（1）获取当前用户所有技能,addAll进skillIds
        List<Integer> oriSkills = personSkillsRepository.findSkillsByUserId(id);
        if (oriSkills != null && oriSkills.size() > 0) {
            skillIds.addAll(oriSkills);
        }
        // (2)删除当前用户所有技能
        personSkillsRepository.deleteByUserId(id);
        //（3）skillIds去重
        List<Integer> listWithoutDup = new ArrayList<Integer>(new HashSet<Integer>(skillIds));
        //（4）写person-skill表
        BtPersonSkills bps = new BtPersonSkills();
        listWithoutDup.forEach(sId -> {
            bps.setSkillId(sId);
            bps.setUserId(id);
            bps.setId(UUIDTool.getUuid());
            personSkillsRepository.save(bps);
        });
        BtPerson person = personRepository.findOne(id);
        BeanUtils.copyProperties(personModifyDTO, person);
        person.setStatus(CommonConstant.PASS);
        personRepository.save(person);
    }

    public Page<BtDemand> demandList(Pageable pageable, HttpSession session) {
        String id = session.getAttribute("user").toString();
        List<BtDemand> page = demandRepository.findDemandByUser(id);
        List<BtDemand> demands = demandRepository.findByOutsourcerShown(CommonConstant.DEMAND_TOTAL);
        for (BtDemand d : demands) {
            page.add(d);
        }
        int start = pageable.getOffset();
        int end = (start + pageable.getPageSize()) > page.size() ? page.size() : (start + pageable.getPageSize());
//        new PageRequest(pageable.getPageNumber(), pageable.getPageSize(),pageable.getSort())
        Page<BtDemand> pages = new PageImpl<>(page.subList(start,end), new PageRequest(pageable.getPageNumber(), pageable.getPageSize()),page.size());
        return pages;
    }

}


